/*
 * Copyright (C), 2002-2016, 苏宁易购电子商务有限公司
 * FileName: BatchTransferData.java
 * Author:   16031333
 * Date:     2016年5月25日 上午10:30:43
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package suning.dto;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bc.trade.channel.suning.util.Digest;
import com.bc.trade.channel.suning.util.HttpClientUtil;
import com.bc.trade.channel.suning.util.RSAUtil;
import com.bc.trade.channel.suning.util.Util;

/**
 * 〈一句话功能简述〉<br>
 * 批量转账 数据拼写
 * 
 * @author 16031333
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class BatchTransferData {

    private String publicKeyIndex = "0001";
    private String signAlgorithm = "RSA";
    private String merchantNo = "70243022";
    private String inputCharset = "UTF-8";

    /**
     * 请求转账网关
     * 
     * @param baseUrl 请求业务数据 batchNum 请求的批次数目 detailNum 单批次中的明细数目
     * @return signature 签名
     * @throws UnsupportedEncodingException
     * @throws java.security.InvalidKeyException
     * @throws KeyManagementException 
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    public String batchWithDraw(String baseUrl) throws InvalidKeyException, NoSuchAlgorithmException,
            InvalidKeySpecException, SignatureException, UnsupportedEncodingException,
            java.security.InvalidKeyException, KeyManagementException {

        String bussinessParam = bulidBatchContentJosn().toJSONString();

        String singnature = calculateSign(bussinessParam);
        String responseStr = HttpClientUtil.post(publicKeyIndex, signAlgorithm, merchantNo, inputCharset, baseUrl,
                singnature, bussinessParam);
        return responseStr;
    }

    /**
     * 计算签名
     * 
     * @param body 请求业务数据
     * @return signature 签名
     * @throws java.security.InvalidKeyException
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    public String calculateSign(String body) throws NoSuchAlgorithmException, InvalidKeySpecException,
            InvalidKeyException, SignatureException, java.security.InvalidKeyException {
        Map<String, String> signMap = new HashMap<String, String>();
        signMap.put("merchantNo", merchantNo);
        signMap.put("publicKeyIndex", publicKeyIndex);
        signMap.put("inputCharset", "UTF-8");
        signMap.put("body", body); 
        //String selfPublicKey  = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANQ6/b8MVIH/LsmzM/IlJRxNeuGHhVME1MNcEZ4Y+dBuvdj5aAE/HS5+WlCANaWWQxZEBIksMIB/ATWAX/pBaYKh10S35ZcGa7vx6FDFfwNSHMjfsbyI+KBoLT3ks2sDQmQMMQ9Wy/xOGZwBzprqA9fZ82qYF5g0CDiwR8mqoh4VAgMBAAECgYAupERN72THKRDcTSD2b4lnXfPKiuEXLLGhuaM5jp2gXCYnADEGTRuZszUgCf1ARfS6ePpSNz71jnPykSMGucd5AqQayNWTgYuqzSkQEZz5un1DQMVsxkIPY/lP/aX3QyX5sw+fSKP5yo3b/RiA69gffv6haY+XT9p9V55PwSy/oQJBAO46QueQQAg4CSKVnxS6Ggqoi6hUBnNLJck6iCVfT1hKRLbeLpjq2554OwDq2Ct/Rbr9/PUzdhtmnKqAf7PXYI0CQQDkEDqV1RyRQvXSOP0clf/YC9tH0BPm4aby5ntlUkdoZq4KawbYO9bBFzqqZG1MTQVQB9pNt7xeBll07QjQOyWpAkA3a1pRIF+lCdQmNYRyf/C69ga3PATcIWlC7NjrSMbelThzCjDw5gH9VZ70Ua3EQLFqFNgZ+sTJDw/3IjmTDtGpAkEAgxTg12WZ+dPmvmGK+XctidumuWvbRITGFC5tFhtod5Usy0ggswARuwHC8lSujYBnYUxiKPFGDzTPDel/e0/DoQJBALJyaLeJgZJk39ACApbIkw2bA0UeyaGIuPYa7r2tKwlC8/51pFa1l/IrbPgLyDFdH4sjOckUhM8cpVgwdddyAmY=";
        String wagKeyString = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANQ6/b8MVIH/LsmzM/IlJRxNeuGHhVME1MNcEZ4Y+dBuvdj5aAE/HS5+WlCANaWWQxZEBIksMIB/ATWAX/pBaYKh10S35ZcGa7vx6FDFfwNSHMjfsbyI+KBoLT3ks2sDQmQMMQ9Wy/xOGZwBzprqA9fZ82qYF5g0CDiwR8mqoh4VAgMBAAECgYAupERN72THKRDcTSD2b4lnXfPKiuEXLLGhuaM5jp2gXCYnADEGTRuZszUgCf1ARfS6ePpSNz71jnPykSMGucd5AqQayNWTgYuqzSkQEZz5un1DQMVsxkIPY/lP/aX3QyX5sw+fSKP5yo3b/RiA69gffv6haY+XT9p9V55PwSy/oQJBAO46QueQQAg4CSKVnxS6Ggqoi6hUBnNLJck6iCVfT1hKRLbeLpjq2554OwDq2Ct/Rbr9/PUzdhtmnKqAf7PXYI0CQQDkEDqV1RyRQvXSOP0clf/YC9tH0BPm4aby5ntlUkdoZq4KawbYO9bBFzqqZG1MTQVQB9pNt7xeBll07QjQOyWpAkA3a1pRIF+lCdQmNYRyf/C69ga3PATcIWlC7NjrSMbelThzCjDw5gH9VZ70Ua3EQLFqFNgZ+sTJDw/3IjmTDtGpAkEAgxTg12WZ+dPmvmGK+XctidumuWvbRITGFC5tFhtod5Usy0ggswARuwHC8lSujYBnYUxiKPFGDzTPDel/e0/DoQJBALJyaLeJgZJk39ACApbIkw2bA0UeyaGIuPYa7r2tKwlC8/51pFa1l/IrbPgLyDFdH4sjOckUhM8cpVgwdddyAmY=";
        String digest = Digest.digest(Digest.mapToString(Digest.treeMap(signMap)));
        PrivateKey privateKey = RSAUtil.getPrivateKey(wagKeyString);
        String signature = RSAUtil.sign(digest, privateKey);
        return signature;
    }

    /**
     * 生成body批次数据
     * 
     * @param
     * @return JSONObject
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    public JSONObject bulidBatchContentJosn() {
        JSONObject contentObject = new JSONObject();
        String batchNo = Util.generalBatchNo();
        contentObject.put("batchNo", batchNo);
        contentObject.put("merchantNo", merchantNo);// 70057241;70056575
        contentObject.put("productCode", "01060000029");
        contentObject.put("totalNum", 1);
        contentObject.put("totalAmount", 100 * 1);// 40*detailNum
        contentObject.put("currency", "CNY");
        contentObject.put("chargeMode", "01");
        contentObject.put("payDate", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        contentObject.put("tunnelData", "{}");

        contentObject.put("goodsType", "220072");
        contentObject.put("remark", "来往货款");
        contentObject.put("notifyUrl", "http://pay.lihaishop.com:8080/notify/suningCallback");
        contentObject.put("batchOrderName", "批量转账");
        contentObject.put("detailData", bulidDetailContentJosn(1));
        return contentObject;
    }

    /**
     * 生成body明细数据
     * 
     * @param
     * @return JSONObject
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    public JSONArray bulidDetailContentJosn(int detailNum) {
        JSONArray detailArray = new JSONArray();
        for (int i = 0; i < detailNum; i++) {
            JSONObject detailObject = new JSONObject();
            detailObject.put("serialNo", Util.generalBatchNo());
            //detailObject.put("receiverLoginName", "10852935016");	//收款方易付宝登录名（仅收款方为个人时传递，最大容量64字节）
            detailObject.put("receiverLoginName", "66668888");	//收款方易付宝登录名（仅收款方为个人时传递，最大容量64字节）
            //detailObject.put("receiverNo", "70056576");	// 收款方商户号，仅收款方为商户时传递
            detailObject.put("receiverType", "PERSON");		// 收款方类型(PERSON：个人；CORP：企业)
            detailObject.put("receiverName", "川普");
            detailObject.put("amount", 100);
            detailObject.put("orderName", "运费险");
            detailObject.put("remark", "来往货款");
            detailArray.add(detailObject);
        }
        return detailArray;
    }

}
